package hust.music.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class ParsingHtml {

	// 全局需要解析的文档
	private Document doc;

	// 构造方法，需要解析的URL
	public ParsingHtml(String endFix) {
		try {
			this.doc = Jsoup.connect(
					"http://www.top100.cn/search/?act=allalbum&keyword="
							+ URLEncoder.encode(endFix, "UTF-8")).timeout(5000).get();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 构造方法，需要解析的文件
	public ParsingHtml(String baseUri, String charset) {
		File input = new File(baseUri);
		try {
			this.doc = Jsoup.parse(input, charset);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 构造方法，需要解析的流
	public ParsingHtml(InputStream is) {
		try {
			String htmlString = inputStream2String(is);
			this.doc = Jsoup.parse(htmlString);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public InputStream getinpInputStream(String selector) {
		InputStream inputStream = null;
		Elements links = doc.select(selector);
		Element srcLink = links.first();
		try {
			URL src = new URL(srcLink.text());
			URLConnection connection = src.openConnection();
			connection.connect();
			inputStream = connection.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return inputStream;
	}

	public String getText(String selector, int index) {
		Element result = null;
		try {
			result = doc.select(selector).get(index);
			result = result.nextElementSibling();
			System.out.println(result);
		} catch (Exception e) {
			return null;
		}

		return result.text();
	}

	public String getImageAddress() {
		try {
			Elements links = doc.select("[src^=http://pic.top100.cn/]");
			String realurl = links.get(0).attr("src");
			return realurl;
		} catch (Exception e) {
			System.out.print(e.getMessage());
			return null;
		}
	}

	public static String inputStream2String(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int i = -1;
		while ((i = is.read()) != -1) {
			baos.write(i);
		}
		return baos.toString();
	}
}
